<?php
namespace app\api\controller;
/*资讯文章控制器*/

use think\facade\Db;
use think\Request;
use app\BaseController;
use app\common\controller\ApiController;
use think\App;

class Article extends ApiController
{

    public function initialize()
    {
        parent::initialize();
        $this->article =  app('app\common\model\media\Articles');
        $this->configuration =  app('app\common\model\system\Configuration');
        $this->store =  app('app\common\model\mall\Store');
        $this->account =  app('app\common\model\mall\Account');
        $this->see_history =  app('app\common\model\system\SeeHistory');
        $this->cate =  app('app\common\model\common\Categories');
        $this->collect =  app('app\common\model\common\Collect');
        $this->user =  app('app\common\model\user\WxUsers');
        $this->user_net =  app('app\common\model\media\UserNet');
        $this->topic =  app('app\common\model\media\Topic');
        $this->comment =  app('app\common\model\media\Comment');
        $this->order =  app('app\common\model\mall\Order');
        $this->collect =  app('app\common\model\common\Collect');


    }

    /*新闻动态 || 校园风采 || 热门新闻*/

    public function index(Request $request){
        switch($request->param('cate')){
            case 1 :$model = $this->article->where('type',1);break;
            case 2 : //获取存在的商家
                $store_ids = $this->store->where('status',1)->column('id');

                $model = $this->article->where('type',2)->whereIn('store_id',$store_ids);

                break;
            case 3 :$model = $this->article->where(['type'=>1,'is_top'=>1]);break;
        }
        if($request->param('name')){
            $model = $model->where('title','like','%'.$request->param('name').'%');
        }


        $res = $model->where('status',1)->order('is_top desc')->order('create_time desc')->order('top_time desc')->paginate($request->param('limit',5));
        $data = [
            'total'     => $res->total(),         // 总记录数
            'current_page'       => $res->currentPage(),   // 当前页码
            'per_page'      => $res->listRows(),      // 每页记录数
            'data'      => $res->items()          // 分页数据
        ];
        return json(['code'=>200,'msg'=>'获取成功','data'=>$data]);
    }


    /**
     * 用户动态
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function topic(Request $request)
    {
        $model = $this->topic;

        if($request->param('name')){
            $model = $model->where('title','like','%'.$request->param('name').'%');
        }
        $res = $model->with('user')->where('status',1)->order('is_top','desc')->order('create_time desc')
            ->paginate($request->param('limit',10));



        foreach ($res->items() as $key => $value) {
            $res->items()[$key]['comment'] = Db::table('bgt_comment')->where('topic_id',$value['id'])->select();
            $res->items()[$key]['images'] = array_filter(explode(',', $value['image']));
        };
        $data = [
            'total'     => $res->total(),         // 总记录数
            'current_page'       => $res->currentPage(),   // 当前页码
            'per_page'      => $res->listRows(),      // 每页记录数
            'data'      => $res->items()          // 分页数据
        ];
        return json(['code'=>200,'msg'=>'获取成功','data'=>$data]);
    }
    /**
     * Show the form for creating a new resource.
     * 发布帖子
     * @return \Illuminate\Http\Response
     */
    public function create_topic(Request $request)
    {
        $data = $request->param(['title','image','info','video','video_map']);
        //验证用户信息

        $userInfo= $this->user->find($request->user_id);

        if(!$userInfo){
            return json(['code'=>202,'msg'=>'用户信息异常']);
        };

        $data['user_id'] = $userInfo->id;
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        $article = $this->topic->save($data);


        return json(['code'=>200,'msg'=>'发布成功']);


    }

    /**
     * Show the form for editing the specified resource.
     * 资讯详情
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function article_detail(Request $request)
    {


        if($request->param('type') == 1){//新闻
            $info = $this->article->find($request->param('id'));
            /*增加一次浏览量*/
            $this->article->where('id',$request->param('id'))->inc('click')->update();

        }else{//商家新闻
            $info = $this->article->find($request->param('id'));
            /*增加一次浏览量*/
            $this->article->where('id',$request->param('id'))->inc('click')->update();
        }

        if(!$info){
            return json(['code'=>202,'msg'=>'帖子不存在']);
        };

        /*浏览记录*/
        /* $history=['user_id'=>$userInfo[0]['id'],'topic_id'=>$request->only('id')['id']];
         if(history::where($history)->first()){
             history::where($history)->update(['updated_at'=>date('Y-m-d H:i:s')]);
         }else{
             $res = history::create($history);
         }*/


        //$info->images= array_filter(explode(',', $info->image));

        // $comment= Comment::order('created_at', 'desc')->where('topic_id',$request->only('id'))->get();

        return json(['code'=>200,'msg'=>'返回成功','data'=>['info'=>$info,/*'comment'=>$comment*/]]);

    }


    /**
     * Show the form for editing the specified resource.
     * 帖子详情
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function topic_detail(Request $request)
    {
        //验证用户信息
        /*dump($this->topic->select());
        dd($this->topic->getLastSql());*/
        $info = $this->topic->with(['user','comment'=>function($query){
            $query->where(['pid'=>0,'status'=>1])->with(['childs'=>function($query){
                $query->where('status',1)->with('user');
            },'user'])->select();
        }])->find($request->param('id'))->toArray();


        if(!$info){
            return json(['code'=>202,'msg'=>'帖子不存在']);
        };

        /*增加一次浏览量*/
        $this->topic->where('id',$request->param('id'))->inc('views')->update();

        $info['ad']=[];
        if($info['image'] !=''){
            $info['images'] = explode(',',$info['image']);
            foreach($info['images'] as $k=>$v){
                $info['ad'][$k]['type'] = 1;
                $info['ad'][$k]['src'] = $v;
            }
        }
//        //实例化redis
//        $redis = Redis::connection();
//        if($request->key && $request->key!="undefined" && $redis->exists(Crypt::decryptString(@$request->key)) ){
//
//            $phone = Crypt::decryptString(@$request->key);
//            $user = WxUsers::where('phone',$phone)->first();
//
//            $request->user_id =$user->id;
//
//
//
//        }else{
//            $request->user_id =0;
//        }
//        /*判断是否点赞*/
//        if(TopicCollect::where(['user_id'=>$request->user_id,'topic_id'=>$request->id])->exists()){
//            $info['is_collect'] = 1;
//        }else{
//            $info['is_collect'] = 0;
//
//        }

        /*判断是否为作者*/
        if($info['user_id'] == $request->user_id){
            $info['is_author'] = 1;
        }else{
            $info['is_author'] = 0;
        }
        $info['video'] !='' && array_push($info['ad'],['type'=>2,'src'=>$info['video']]);

        return json(['code'=>200,'msg'=>'返回成功','data'=>['info'=>$info]]);

    }

    /*发布评论*/
    public function push_comment(Request $request){
        $data=$request->param(['topic_id','content']);
        $info = $this->topic->find($request->param('topic_id'));

        if(!$info){
            return json(['code'=>202,'msg'=>'帖子不存在']);
        };
        $data['from_uid'] = $request->user_id;

        $article = $this->comment->save($data);
        if($article){
            $this->topic->where('id',$request->param('topic_id'))->inc('comments')->update();
            return json(['code'=>200,'msg'=>'评论成功']);
        }
        return json(['code'=>202,'msg'=>'评论失败']);
    }

    /*回复评论*/

    public function answer_comment(Request $request){
        $data=$request->only(['content','pid']);

        $data['from_uid'] = $request->user_id;
        //查询单挑评论记录
        $comment = Comment::findOrFail($request->pid);
        $data['from_uid'] = $request->user_id;
        $data['review_id'] = $comment['from_uid'];
        $data['topic_id'] = $comment['topic_id'];
        $article = Comment::create($data);
        if($article){
            $this->topic->where('id',$request->topic_id)->inc('comments')->update();
            return json(['code'=>200,'msg'=>'评论成功']);
        }
        return json(['code'=>202,'msg'=>'评论失败']);
    }


    /*我的发布*/
    public function my_topic(Request $request){
        $model = $this->topic;

        $model = $model->where('user_id',$request->user_id);
        switch($request->param('status')){
            case 0:$model = $model->where('status',1);break;//已发布
            case 1:$model = $model->where('status',0);break;//待审核
            case 2:$model = $model->where('status',2);break;//驳回
        }
        $res = $model->order('create_time','desc')->paginate($request->param('limit',10));
        $data = [
            'total'     => $res->total(),         // 总记录数
            'current_page'       => $res->currentPage(),   // 当前页码
            'per_page'      => $res->listRows(),      // 每页记录数
            'data'      => $res->items()          // 分页数据
        ];
        return json(['code'=>200,'msg'=>'获取成功','data'=>$data]);
    }

    /*帖子点赞*/
    public function topic_collect(Request $request){
        try{


            if($info = $this->collect->where(['user_id'=>$request->user_id,'type'=>4,'account_id'=>$request->param('topic_id')])->find()){
                $info->delete();
                $this->topic->where('id',$request->param('topic_id'))->dec('collect',1)->update();
            }else{
                $this->collect->save(['type'=>4,'user_id'=>$request->user_id,'account_id'=>$request->param('topic_id')]);
                $this->topic->where('id',$request->param('topic_id'))->inc('collect',1)->update();
            }
            $collect = $this->topic->where('id',$request->param('topic_id'))->value('collect');
            return json(['code'=>200,'msg'=>'成功','data'=>['data'=>$collect]]);
        }catch(\Exception $e){
            return json(['code'=>202,'msg'=>$e->getMessage()]);
        }

    }

    /*帖子转发*/
    public function topic_trans(Request $request){
        try{

            $this->topic->where('id',$request->topic_id)->inc('trans')->update();

            return json(['code'=>200,'msg'=>'成功']);
        }catch(\Exception $e){
            return json(['code'=>202,'msg'=>$e->getMessage()]);
        }

    }
}